package com.bs.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.LazyDynaBean;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.bs.bean.Item;
import com.bs.bean.Maoli;
import com.bs.bean.Person;
import com.bs.dao.ItemDAO;
import com.bs.dao.MaoliDAO;
import com.bs.dao.PersonDAO;
import com.bs.dao.ProductDAO;
import com.bs.service.ItemService;

public class ItemServiceImpl extends SqlMapClientDaoSupport implements ItemService {

	private ItemDAO itemDao;
	
	private MaoliDAO maoliDao; 
	
	private PersonDAO personDao;
	
	private ProductDAO productDao;
	
	
	
	public ProductDAO getProductDao() {
		return productDao;
	}

	public void setProductDao(ProductDAO productDao) {
		this.productDao = productDao;
	}

	public PersonDAO getPersonDao() {
		return personDao;
	}

	public void setPersonDao(PersonDAO personDao) {
		this.personDao = personDao;
	}

	public MaoliDAO getMaoliDao() {
		return maoliDao;
	}

	public void setMaoliDao(MaoliDAO maoliDao) {
		this.maoliDao = maoliDao;
	}

	public ItemDAO getItemDao() {
		return itemDao;
	}

	public void setItemDao(ItemDAO itemDao) {
		this.itemDao = itemDao;
	}

	@Override
	public void save(Item item) throws Exception{
		Item i = calculateItem(item);
		this.itemDao.save(i);
	}

	@Override
	public List<Item> findAll(int start, int limit) {
		return this.itemDao.findAll(start, limit);
	}
	
	
	@Override
	public List<Item> findAll(String start, String end, String type) {
		return this.itemDao.findAll(start, end, type);
	}

	@Override
	public List<Item> findAll() {
		return this.itemDao.findAll();
	}

	@Override
	public int batchDelete(String ids){
		return this.itemDao.batchDelete(ids);
	}


	@Override
	public int update(Item item, String type) throws Exception{
		if(type.equals("sell")){
			Item i = calculateItem(item);
			return this.itemDao.update(i, type);
		}else{
			return this.itemDao.update(item, type);
		}
		
	}

	@Override
	public int totalCount() {
		return this.itemDao.totalCount();
	}
	
	
	@Override
	public List<Item> sumBySeason(String start, String end, String type) {
		return  this.itemDao.sumBySeason(start, end, type);
	}

	
	
	@Override
	public List<LazyDynaBean> busiBonusBySeason(String start, String end) {
		List<Person> persons = this.personDao.query(null);
		List<Item> sellList = this.itemDao.busiBonusBySeason(start, end, "sell");
		List<Item> backList = this.itemDao.busiBonusBySeason(start, end, "back");
		List<LazyDynaBean> resultList = new ArrayList<LazyDynaBean>();
		for(Person person : persons){
			LazyDynaBean bean = new LazyDynaBean();
			bean.set("person", person.getName());
			bean.set("base", person.getBase());
			if(sellList.size()==0){
				bean.set("sellSum",0.0);
				bean.set("sellAword", 0.0);
			}
			for(Item sellsum : sellList){
				if(person.getName().equals(sellsum.getPerson().getName())){
					bean.set("sellSum",sellsum.getSellSum());
					bean.set("sellAword", sellsum.getBusinessman());
					break;
				}else{
					bean.set("sellSum",0.0);
					bean.set("sellAword", 0.0);
				}
			}
			if(backList.size()==0){
				bean.set("backSum",0.0);
				bean.set("backAword", 0.0);
			}
			for(Item backsum : backList){
				if(person.getName().equals(backsum.getPerson().getName())){
					bean.set("backSum", backsum.getSellSum());
					bean.set("backAword", backsum.getBusinessman());
					break;
				}else{
					bean.set("backSum",0.0);
					bean.set("backAword", 0.0);
				}
			}
			resultList.add(calculateSum(bean));
		}
		
		return resultList;
	}

	
	
	@Override
	public List<LazyDynaBean> supportBonusBySeason(String start, String end) {
		
		List<Item> sellList = this.itemDao.supportBonusBySeason(start, end, "sell");
		List<Item> backList = this.itemDao.supportBonusBySeason(start, end, "back");
		List<LazyDynaBean> resultList = new ArrayList<LazyDynaBean>();
		Map<String, LazyDynaBean> map = new HashMap<String, LazyDynaBean>();
		for(Item sellItem : sellList){
			LazyDynaBean bean = new LazyDynaBean();
			String productType = sellItem.getProduct().getType();
			bean.set("sellSum", sellItem.getSellSum());
			bean.set("sellAword", sellItem.getTechSupport());
			bean.set("backSum", 0.0);
			bean.set("backAword", 0.0);
			bean.set("person", this.personDao.findBySupportType(productType));
			bean.set("product", sellItem.getProduct());
			map.put(productType, bean);
		}
		for(Item backItem : backList){
			String productType = backItem.getProduct().getType();
			
			if(map.get(productType)!=null){
				LazyDynaBean bean = map.get(productType);
				bean.set("backSum", backItem.getSellSum());
				bean.set("backAword", backItem.getTechSupport());
				map.put(productType, bean);
			}else{
				LazyDynaBean bean = new LazyDynaBean();
				bean.set("sellSum", 0.0);
				bean.set("sellAword", 0.0);
				bean.set("backSum", backItem.getSellSum());
				bean.set("backAword", backItem.getTechSupport());
				bean.set("person", this.personDao.findBySupportType(productType));
				bean.set("product", backItem.getProduct());
				map.put(productType, bean);
			}
		}
		
		Set<String> keyset = map.keySet();
		for(Iterator<String> it = keyset.iterator();it.hasNext(); ){
			String key = it.next();
			LazyDynaBean bean = map.get(key);
			resultList.add(this.calculateSum(bean));
		}
		return resultList;
	}

	
	@Override
	public List<LazyDynaBean> managerBonusBySeason(String start, String end) {
		List<Item> sellList = this.itemDao.managerBonusBySeason(start, end, "sell");
		List<Item> backList = this.itemDao.managerBonusBySeason(start, end, "back");
		List<LazyDynaBean> resultList = new ArrayList<LazyDynaBean>();
		Map<String, LazyDynaBean> map = new HashMap<String, LazyDynaBean>();
		for(Item sellItem : sellList){
			LazyDynaBean bean = new LazyDynaBean();
			String productType = sellItem.getProduct().getType();
			String managerName = sellItem.getPerson().getManager().getName();
			String key = productType+"_"+managerName;
			bean.set("sellSum", sellItem.getSellSum());
			bean.set("sellAword", sellItem.getManager());
			bean.set("backSum", 0.0);
			bean.set("backAword", 0.0);
			bean.set("person", sellItem.getPerson().getManager());
			bean.set("product", sellItem.getProduct());
			map.put(key, bean);
		}
		for(Item backItem : backList){
			String productType = backItem.getProduct().getType();
			String managerName = backItem.getPerson().getManager().getName();
			String key = productType+"_"+managerName;
			if(map.get(key)!=null){
				LazyDynaBean bean = map.get(key);
				bean.set("backSum", backItem.getSellSum());
				bean.set("backAword", backItem.getManager());
				map.put(key, bean);
			}else{
				LazyDynaBean bean = new LazyDynaBean();
				bean.set("sellSum", 0.0);
				bean.set("sellAword", 0.0);
				bean.set("backSum", backItem.getSellSum());
				bean.set("backAword", backItem.getManager());
				bean.set("person", backItem.getPerson().getManager());
				bean.set("product", backItem.getProduct());
				map.put(key, bean);
			}
		}
		Set<String> keyset = map.keySet();
		for(Iterator<String> it = keyset.iterator();it.hasNext(); ){
			String key = it.next();
			LazyDynaBean bean = map.get(key);
			resultList.add(this.calculateSum(bean));
		}
		return resultList;
	}

	
	
	
	@Override
	public List<LazyDynaBean> teamBonusBySeason(String start, String end) {
		List<Item> sellList = this.itemDao.teamBonusBySeason(start, end, "sell");
		List<Item> backList = this.itemDao.teamBonusBySeason(start, end, "back");
		List<LazyDynaBean> resultList = new ArrayList<LazyDynaBean>();
		Map<String, LazyDynaBean> map = new HashMap<String, LazyDynaBean>();
		for(Item sellItem : sellList){
			LazyDynaBean bean = new LazyDynaBean();
			String productType = sellItem.getProduct().getType();
			bean.set("sellSum", sellItem.getSellSum());
			bean.set("sellAword", sellItem.getTeam());
			bean.set("backSum", 0.0);
			bean.set("backAword", 0.0);
			bean.set("person", this.personDao.findBySupportType(productType));
			bean.set("product", sellItem.getProduct());
			map.put(productType, bean);
		}
		for(Item backItem : backList){
			String productType = backItem.getProduct().getType();
			
			if(map.get(productType)!=null){
				LazyDynaBean bean = map.get(productType);
				bean.set("backSum", backItem.getSellSum());
				bean.set("backAword", backItem.getTeam());
				map.put(productType, bean);
			}else{
				LazyDynaBean bean = new LazyDynaBean();
				bean.set("sellSum", 0.0);
				bean.set("sellAword", 0.0);
				bean.set("backSum", backItem.getSellSum());
				bean.set("backAword", backItem.getTeam());
				bean.set("person", this.personDao.findBySupportType(productType));
				bean.set("product", backItem.getProduct());
				map.put(productType, bean);
			}
		}
		
		Set<String> keyset = map.keySet();
		for(Iterator<String> it = keyset.iterator();it.hasNext(); ){
			String key = it.next();
			LazyDynaBean bean = map.get(key);
			resultList.add(this.calculateSum(bean));
		}
		return resultList;
	}

	
	
	
	@Override
	public List<LazyDynaBean> sumAllPersonBySeason(String start, String end) {
		List<LazyDynaBean> list = new ArrayList<LazyDynaBean>();
		List<Person> persons= this.personDao.query(null);
		for(Person person : persons){
			LazyDynaBean result = new LazyDynaBean();
			result.set("name", person.getName());
			int personId = person.getId();
			Item sellItem = this.itemDao.sumByPerson(start, end, "sell", personId);
			Item backItem = this.itemDao.sumByPerson(start, end, "back", personId);
			LazyDynaBean bean = new LazyDynaBean();
			bean.set("base", person.getBase());
			bean.set("sellSum", sellItem.getSellSum());
			bean.set("sellAword", sellItem.getBusinessman());
			bean.set("backSum", backItem.getSellSum());
			bean.set("backAword", backItem.getBusinessman());
			double busiResult = (Double) calculateSum(bean).get("resutlBonus");
			result.set("busiResult", busiResult);
			String supportType = person.getSupportType();
			if(supportType!=null){
				Item supportSell = this.itemDao.sumBySupportType(start, end, "sell", supportType);
				Item supportBack = this.itemDao.sumBySupportType(start, end, "back", supportType);
				double sellSupport = supportSell.getTechSupport();
				double backSupport = supportBack.getTechSupport();
				result.set("supportResult", (sellSupport+backSupport)/2);
			}else{
				result.set("supportResult", 0.0);
			}
			
			int position = person.getPosition();
			if(position == 1){
				Item managerSell = this.itemDao.sumByManager(start, end, "sell", personId);
				Item managerBack = this.itemDao.sumByManager(start, end, "back",personId);
				double sellManager = managerSell.getManager();
				double backManager = managerBack.getManager();
				result.set("managerResult", (sellManager+backManager)/2);
			}else{
				result.set("managerResult", 0.0);
			}
			result.set("bonusSum", (Double)result.get("busiResult")+(Double)result.get("supportResult")+(Double)result.get("managerResult"));
			list.add(result);
		}
		return list;
	}

	private LazyDynaBean calculateSum(LazyDynaBean bean){
		double sellbacksum = (Double)bean.get("sellSum") + (Double)bean.get("backSum");
		double sellbackAword = (Double)bean.get("sellAword") + (Double)bean.get("backAword");
		bean.set("sellbacksum", sellbacksum);
		bean.set("sellbacksumhalf", (int)sellbacksum/2);
		bean.set("sellbackAword", sellbackAword);
		bean.set("sellbackAwordhalf", (int)sellbackAword/2);
		if(bean.get("base")!=null){
			int base = (Integer) bean.get("base");
			double resutlBonus = 0.0;
			if(sellbacksum!=0.0)
				resutlBonus = sellbackAword/2 - (sellbackAword/sellbacksum)*base;
			bean.set("resutlBonus", resutlBonus);
		}
		return bean;
	}
	
	private double maoli2proportion(double maoli) throws Exception{
		if(maoli >= 1.5){
			maoli = 1.5;
		}else if(maoli < 1.5 && maoli >= 1.2){
			maoli = 1.2;
		}else if(maoli < 1.2 && maoli >= 1.0){
			maoli = 1.0;
		}else if(maoli <1.0 && maoli >=0.5){
			maoli = Math.floor(maoli * 10) / 10;
		}else if(maoli <0.5 && maoli >=0.1){
			maoli = Math.floor(maoli * 20) / 20;
		}else{
			return 0;
		}
		
		Maoli m = this.maoliDao.findByMaoli(maoli);
		return m.getProportion();
	}
	
	public Item  calculateItem(Item item)  throws Exception{
		double sellPrice = item.getSellPrice();//售价
		double sellCount = item.getCount();//销售数量
		double sellSum = sellPrice * sellCount;//销售总金额
		double buyPrice = item.getBuyPrice(); //进价
		double shunjia = sellPrice / buyPrice - 1; //顺加
		double maoli = (sellPrice - buyPrice) / buyPrice; //毛利贡献率
		double proportion = this.maoli2proportion(maoli);//提成比例
		double sum = sellSum * proportion; // 合计金额
		double businessman = sum * 0.6; //业务经理奖
		double techSupport = sum * 0.1; //技术支持奖
		double manager = sum * 0.1; //事业部奖励将
		double team = sum * 0.2; //团队奖 
		item.setSellSum(sellSum);
		item.setShunjia(shunjia);
		item.setProportion(proportion);
		item.setSum(sum);
		item.setBusinessman(businessman);
		item.setTechSupport(techSupport);
		item.setManager(manager);
		item.setTeam(team);
		return item;
	}

	@Override
	public List<Item> query(Item item) {
		return this.itemDao.query(item);
	}
	
}